$(function () {
    if ($.browser.msie && $.browser.version < 10) {
        alert("抱歉，由于您的浏览器版本太低，将导致本站功能无法正常运行。\n请下载最新版本的浏览器。");
    }
    var queryWrap = $(".query_wrap");
    var queryList2 = $(".query1ist_2");
    var queryWrap3 = $(".q3_wrap");
    var queryList3 = $(".query1ist_3");
    var querySection3 = $(".q3_wrap .query_section");
    var queryResult = $(".query_result");
    var queryResultWrap = $(".query_result .query_data_wrap");
    var dataList = $(".data_list");
    var typhoonDetail = $(".typhoon_detail");
    var statisticalResult = $(".statistical_result"); //统计结果
    var queryDivision2 = $(".q2_division");
    var currentMonitor = $(".current_monitor");
    var typhoonHistoryInfo = $(".typhoon_history");
    querySection3.hide();
    queryResult.hide();
    $(".result_wrap").show();
    statisticalResult.hide();
    typhoonDetail.hide();

    //定义台风起始结束时间
    var startTime = "1949-01-01 00:00:00";
    var endTime = new Date().getFullYear() + "-"+ (new Date().getMonth() + 1)+ "-"+ new Date().getDate() + " 23:59:59";

    //清除样式
    function clearStyle(name) {
        typhoonMap.drawn.clearDrawLayer(); //取消绘制图
        typhoonMap.resetTyphoonLayers(); //取消台风路径
        $("input[type='text']").val("");
        $("input[type='hidden']").val("");
        $(".query1ist_3 select").find("option:first").prop("selected", "selected");
        $(".query_section_strength .query_search_tystr :checkbox").prop("checked", false);
        $(".q3_wrap .toggle_btn").find("p").html("隐藏查询条件");
        $(".query_result .toggle_btn").find("p").html("隐藏查询结果");
        $(".toggle_icon").removeClass("toggle_btn_transform");
        queryResult.find(".typhoon_no").removeClass("typhoon_no_color").siblings().removeClass("typhoon_name_color");
        queryList3.removeClass("visible_hide");
        queryResultWrap.removeClass("visible_hide");
        typhoonDetail.removeClass("visible_hide");
        queryWrap3.hide();
        querySection3.hide();
        queryResult.hide();
        typhoonDetail.hide();
        if (name == "realtime") {  //实时监测的默认样式
            typhoonMap.clearCircle();
            currentMonitor.find(".typhoon_no").removeClass("typhoon_no_color").siblings().removeClass("typhoon_name_color");
            currentMonitor.hide();

        } else if (name == "normal") { //一般查询的默认样式
            $(".query1ist_2 p").removeClass("active");
            queryList2.removeClass("visible_hide");
            queryList2.hide();
            $(".query_select_point").hide();//经纬点

        } else if (name == "windfarm") { //风电场查询的默认样式
            $("textarea").text("");
            $(".draw_polygon").hide();
            $(".typhoon_detail .query_data").css("max-height", "405px");
            statisticalResult.removeClass("visible_hide");
            statisticalResult.hide();
            $(".query_select_cicle").hide();//经纬圆形

        } else if (name == "division") { //区划查询的默认样式
            $(".division_option").removeClass("division_style");
            queryDivision2.hide();
            typhoonMap.clearShp();
        } else {  //历史台风查询的默认样式
            typhoonHistoryInfo.hide();
            $("#data_list_ic").find(".typhoon_no").removeClass("typhoon_no_color").siblings().removeClass("typhoon_name_color");
            $("#query_ic_label").empty();
            $("#query_ic_detail").empty();
        }
        $(".query_item p").removeClass("selected");
    }

    //恢复默认选择状态
    function defaultSelection(value) {
        var radioEl = [$(".query_select_cicle :radio"), $(".query_section_time :radio"), $(".query_section_strength .query_select :radio"), $("input[name='strengthOrValue']")];
        var targetEl = [$(".query_section_pos .query_search_pos"), $(".query_section_time .query_search_time"), $(".query_section_strength .query_search_tystr")];
        var radioPointEl = $(".query_select_point :radio");
        if (value == "windfarm") { //恢复风电场默认显示
            $.each(radioEl, function () {
                $(this).first().prop("checked", true);
                $(this).last().prop("checked", false);
            });
            $.each(targetEl, function () {
                $(this).first().show();
                $(this).last().hide();
            });
        } else {  //一般查询项默认显示
            if (value == 1) { //经纬点
                radioPointEl.first().prop("checked", true);
                radioPointEl.last().prop("checked", false);
                targetEl[0].first().show();
                targetEl[0].last().hide();
            } else if (value == 2) { //时间
                radioEl[1].first().prop("checked", true);
                radioEl[1].last().prop("checked", false);
                targetEl[1].first().show();
                targetEl[1].last().hide();
            } else if (value == 4) { //台风强度
                radioEl[2].first().prop("checked", true);
                radioEl[2].last().prop("checked", false);
                radioEl[3].first().prop("checked", true);
                radioEl[3].last().prop("checked", false);
                targetEl[2].first().show();
                targetEl[2].last().hide();
            }
        }
    }

    //实时监控
    $('.query_realtime p').click(function () {
        if ($(this).parent().siblings().find("p").hasClass("selected")) {
            clearStyle($(".selected").attr("query_name"));
        }
        if (!$(this).hasClass("selected")) {
            $(this).addClass("selected");
            $.ajax({
                url: '/tfData/tf_path_data/realtime.ajax',
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    $(this).attr("tfbh", data.tfbh);
                    typhoonMap.drawTyphoon_(data);
                    var ddd = typhoonMap.crossCheck(typhoonMap.t_layers[data.tfbh].t_path_layers, typhoonMap.t_guardLine);
                    if (ddd.geometries.length > 0) {
                        $(".typhoon_info").html("台风已进入24小时警戒线，请做好台风防护准备").css("color", "#ff0000");
                        currentMonitor.show();
                        drawCircleQuery();
                    }
                }
            });
        } else {
            clearStyle($(this).attr("query_name"));
        }

    });

    //一般查询
    $(".query_normal p").click(function () {
        if ($(this).parent().siblings().find("p").hasClass("selected")) {
            clearStyle($(".selected").attr("query_name"));
        }
        if (!$(this).hasClass("selected")) {
            $(this).addClass("selected");
            $("#start_time").html(startTime);
            $("#end_time").html(endTime);
            $(".query_select_point").show(); //经纬点显示
            $(".query_select_cicle").hide(); //经纬圆形隐藏
            queryList2.show();
        } else {
            clearStyle($(this).attr("query_name"));
        }
    });

    //风电场台风查询
    $(".query_windfarm p").click(function () {
        if ($(this).parent().siblings().find("p").hasClass("selected")) {
            clearStyle($(".selected").attr("query_name"));
        }
        if (!$(this).hasClass("selected")) {
            $(this).addClass("selected");
            $("#start_time").html(startTime);
            $("#end_time").html(endTime);
            defaultSelection("windfarm");
            $(".query_select_cicle").show(); //经纬圆形显示
            $(".query_select_point").hide(); //经纬点隐藏
            $(".query_section_pos").show();
            $(".query_section_time").show();
            $(".query_section_strength").show();
            $(".typhoon_detail .query_data").css("max-height", "190px");
            queryWrap3.show();
        } else {
            clearStyle($(this).attr("query_name"));
        }
    });

    //区划查询
    $(".query_division p").click(function () {
        if ($(this).parent().siblings().find("p").hasClass("selected")) {
            clearStyle($(".selected").attr("query_name"));
        }
        if (!$(this).hasClass("selected")) {
            $(this).addClass("selected");
            queryDivision2.show();
        } else {
            clearStyle($(this).attr("query_name"));
        }
    });

    //历史台风查询
    $(".query_typhoonall p").click(function () {
        if ($(this).parent().siblings().find("p").hasClass("selected")) {
            clearStyle($(".selected").attr("query_name"));
        }
        if (!$(this).hasClass("selected")) {
            $(this).addClass("selected");
            typhoonHistoryInfo.show();
        } else {
            clearStyle($(this).attr("query_name"));
        }
    });

    //区划项样式切换
    $(".division_option").click(function () {
        var divisionName = $(this).attr("divison_name");
        if (!$(this).hasClass("division_style")) {
            typhoonMap.clearShp();
            if (divisionName == "d50") {
                typhoonMap.draw50Shp();
            } else if (divisionName == "d70") {
                typhoonMap.draw70Shp();
            } else {
                typhoonMap.drawBizhiShp();
            }
            $(this).addClass("division_style").siblings().removeClass("division_style");
        }
    });

    //二级查询切换
    $(".query1ist_2 p").click(function () {
        var targetEl = $(".q3_wrap .query_section");
        var clickEl = $(".query1ist_2 p");
        var index = clickEl.index($(this));
        var activeEl = $(".query1ist_2 .active");
        if ((!clickEl.hasClass("active"))) {
            queryWrap3.show();
        }
        if (!$(this).hasClass("active")) {
            $(this).addClass("active");
            $(targetEl[index]).show();
            defaultSelection(index);
        } else {
            if (activeEl.length > 1) {
                $(this).removeClass("active");
                $(targetEl[index]).hide();
                clearInputVal(index);
            }
        }
    });

    //取消页面绘制图形
    $(".cancel_draw").click(function () {
        typhoonMap.drawn.clearDrawLayer();
    });

    //清除输入状态
    function clearInputVal(index) {
        if (index == 0 || index == 1) {
            $(querySection3[index]).find(":text").val("");
        } else if (index == 2) {
            $("#start_time").html(startTime);
            $("#end_time").html(endTime);
            $(".query_section_time select").find("option:first").prop("selected", "selected");
            $(".query_section_time input[type='hidden']").val("");
        } else if (index == 3) {
            $(querySection3[index]).find(":text").val("");
            $(".query_section_place select").find("option:first").prop("selected", "selected");
            $(".query_section_place input[type='hidden']").val("");
        } else {
            $(querySection3[index]).find(":text").val("");
            $(".q3_wrap .query_section_strength .query_search_tystr :checkbox").prop("checked", false);
            $(".query_section_strength input[type='hidden']").val("");
        }
    }

    //查询条件按钮切换
    $(".q3_wrap .toggle_btn").click(function () {
        if (!queryList3.hasClass("visible_hide")) {
            if ($(".query_normal p").hasClass("selected")) {
                queryList2.addClass("visible_hide");
            }
            $(this).find("p").html("显示查询条件");
            $(this).find(".toggle_icon").addClass("toggle_btn_transform");
            queryList3.addClass("visible_hide");
        } else {
            if ($(".query_normal p").hasClass("selected")) {
                queryList2.removeClass("visible_hide");
            }
            $(this).find("p").html("隐藏查询条件");
            $(this).find(".toggle_icon").removeClass("toggle_btn_transform");
            queryList3.removeClass("visible_hide");
        }
    });

    //查询结果按钮切换
    $(".query_result .toggle_btn").click(function () {
        if (!queryResultWrap.hasClass("visible_hide")) {
            if ($(".query_windfarm p").hasClass("selected")) {
                statisticalResult.addClass("visible_hide");
            }
            $(this).find("p").html("显示查询结果");
            $(this).find(".toggle_icon").addClass("toggle_btn_transform");
            queryResultWrap.addClass("visible_hide");
            typhoonDetail.addClass("visible_hide");
        } else {
            if ($(".query_windfarm p").hasClass("selected")) {
                statisticalResult.removeClass("visible_hide");
            }
            $(this).find("p").html("隐藏查询结果");
            $(this).find(".toggle_icon").removeClass("toggle_btn_transform");
            queryResultWrap.removeClass("visible_hide");
            typhoonDetail.removeClass("visible_hide");
        }
    });

    //查询结果的全选反选功能
    var selectFunction = {
        selectAll: function (clickEl, targetEl) {  //全选
            clickEl.click(function () {
                targetEl.find(".typhoon_no").each(function () {
                    if (!$(this).hasClass("typhoon_no_color")) {
                        $(this).addClass("typhoon_no_color").siblings().addClass("typhoon_name_color");
                    }
                });
            });
        },
        selectNone: function (clickEl, targetEl) {  //取消
            clickEl.click(function () {
                targetEl.find(".typhoon_no").removeClass("typhoon_no_color").siblings().removeClass("typhoon_name_color");
            });
        },
        selectReverse: function (clickEl, targetEl) {
            clickEl.click(function () {  //反选
                targetEl.find(".typhoon_no").each(function () {
                    if ($(this).hasClass("typhoon_no_color")) {
                        $(this).removeClass("typhoon_no_color").siblings().removeClass("typhoon_name_color");
                    } else {
                        $(this).addClass("typhoon_no_color").siblings().addClass("typhoon_name_color");
                    }
                });
            });
        }
    };

    //实时监测全选反选
    selectFunction.selectAll($("#selectall"), currentMonitor);
    selectFunction.selectReverse($("#selectreverse"), currentMonitor);
    selectFunction.selectNone($("#selectnone"), currentMonitor);

    //查询全选反选
    selectFunction.selectAll($("#checkall"), queryResult);
    selectFunction.selectReverse($("#checkreverse"), queryResult);
    selectFunction.selectNone($("#checknone"), queryResult);

    //实时监测隐藏切换
    $(".current_monitor .cm_toggle").toggle(function () {
        $(".p1_font").html("显");
        $(".p2_font").html("示");
        $(".toggle_font").html("&lt;");
        $(".current_monitor .query_data_wrap").hide();
        typhoonDetail.addClass("visible_hide");
    }, function () {
        $(".p1_font").html("隐");
        $(".p2_font").html("藏");
        $(".toggle_font").html("&gt;");
        $(".current_monitor .query_data_wrap").show();
        typhoonDetail.removeClass("visible_hide");
    });

    $(".query_select_point :radio").click(function () { //经纬点切换
        var clickEl = $(".query_select_point :radio");
        var targetEl = $(".query_section_pos .query_search_pos");
        var index = clickEl.index($(this));
        clickEl[1 - index].checked = false;
        targetEl[index].style.display = "block";
        targetEl[1 - index].style.display = "none";
    });

    $(".query_select_cicle :radio").click(function () {  //经纬圆形切换
        var clickEl = $(".query_select_cicle :radio");
        var target1 = $(".q3_wrap .query_search_pos");
        var target2 = $(".draw_polygon");
        var index = clickEl.index($(this));
        clickEl[1 - index].checked = false;
        if (index == 0) {
            target1.eq(0).show();
            target2.hide();
            $("#area_polygon_val").val("");
        } else {
            target1.eq(0).hide();
            target2.show();
            $("#area_polygon_val").val($("#area_polygon").text());
        }
    });

    $(".query_section_time :radio").click(function () {  //时间切换
        var clickEl = $(".query_section_time :radio");
        var target = $(".q3_wrap .query_search_time");
        var index = clickEl.index($(this));
        var bTime = $("#beginTime");
        var eTime = $("#endTime");
        var byear = $("#byear").find(":selected").val();
        var bmonth = $("#bmonth").find(":selected").val();
        var bday = $("#bday").find(":selected").val();
        var eyear = $("#eyear").find(":selected").val();
        var emonth = $("#emonth").find(":selected").val();
        var eday = $("#eday").find(":selected").val();
        clickEl[1 - index].checked = false;
        target.eq(index).show();
        target.eq(1 - index).hide();
        if (index == 0) {
            bTime.val($("#start_time").html());
            eTime.val($("#end_time").html());
        } else {
            bTime.val(byear + "-" + bmonth + "-" + bday + " 00:00:00");
            eTime.val(eyear + "-" + emonth + "-" + eday + " 23:59:59");
        }
    });

    //台风单选项切换
    $(".query_section_strength .query_select :radio").click(function () {
        var clickEl = $(".query_section_strength .query_select :radio");
        var index = clickEl.index($(this));
        clickEl[1 - index].checked = false;
    });

    //台风强度项切换
    $("input[name='strengthOrValue']").click(function () {
        var clickEl = $("input[name='strengthOrValue']");
        var index = clickEl.index($(this));
        var targetEl = $(".query_section_strength .query_search_tystr");
        clickEl[1 - index].checked = false;
        targetEl[index].style.display = "block";
        targetEl[1 - index].style.display = "none";
    });

    //统计结果样式切换
    $(".statistical_option_l").addClass("toggle_style");
    $(".statistical_result .typhoon_table").eq(1).hide();
    $(".statistical_option p").click(function () {
        var index = $(".statistical_option p").index($(this));
        var statisTable = $(".statistical_result .typhoon_table");
        if (!$(this).hasClass("toggle_style")) {
            $(this).addClass("toggle_style");
            $(".statistical_option p").eq(1 - index).removeClass("toggle_style");
            statisTable.eq(1 - index).hide();
            statisTable.eq(index).show();
        }
    });

    //台风路径信息选中状态
    $("#simple_detail").on("click", "tr", function () {
        $(this).addClass("tr_click").siblings().removeClass("tr_click");
    });

    //工具栏切换
    $(".toolslist_toggle").toggle(function () {
        $(this).addClass("toggle_btn_transform").siblings().hide();
    }, function () {
        $(this).removeClass("toggle_btn_transform").siblings().show();
    });

    //图例显示隐藏
    $(".lf_title").on("click", function () {
        var index = $(".lf_title").index($(this));
        var targetEl = $(".lf_c");
        if (!$(this).hasClass("lf_title_style")) {
            $(this).addClass("lf_title_style");
            $(targetEl[index]).show();
        } else {
            $(this).removeClass("lf_title_style");
            $(targetEl[index]).hide();
        }
    });

    //预报线显示与隐藏
    $(".forcast_content :checkbox").on("click", function () {
        var flag = $(this).prop("checked");
        var forcastName = $(this).attr("forcast_name");
        typhoonMap.toogleForcastLayers(forcastName, flag);
    });

    //日期初始化
    var layDateParameter1 = {
        elem: "#start_time",
        format: 'YYYY-MM-DD hh:mm:ss', //日期格式
        festival: false, //显示节日
        istime: true, //是否开启时间选择
        min: startTime, //最小日期
        max: endTime, //最大日期
        event: 'click', //触发事件
        isclear: true, //是否显示清空
        istoday: false, //是否显示今天
        issure: true, //是否显示确认
        start: '2010-1-1 00:00:00',  //开始日期
        fixed: false, //是否固定在可视区域
        choose: function (datas) { //选择日期完毕的回调
            var name = this.elem.substring(1);
            $('#beginTime').val(datas);
        }
    };
    var layDateParameter2 = {
        elem: "#end_time",
        format: 'YYYY-MM-DD hh:mm:ss', //日期格式
        festival: false, //显示节日
        istime: true, //是否开启时间选择
        min: startTime, //最小日期
        max: endTime, //最大日期
        event: 'click', //触发事件
        isclear: true, //是否显示清空
        istoday: false, //是否显示今天
        issure: true, //是否显示确认
        start: '2010-1-1 00:00:00',  //开始日期
        fixed: false, //是否固定在可视区域
        choose: function (datas) { //选择日期完毕的回调
            var name = this.elem.substring(1);
            $('#endTime').val(datas);
        }
    };
    laydate(layDateParameter1);
    laydate(layDateParameter2);
    //年月日生成
    dateListBulid($('select[name=byear]'), $('select[name=bmonth]'), $('select[name=bday]'));
    dateListBulid($('select[name=eyear]'), $('select[name=emonth]'), $('select[name=eday]'));
    function dateListBulid(yearEl, monthEl, dayEl) {
        var i = 1949;
        var max = new Date().getFullYear();
        var dropList;
        for (i; i <= max; i++) {
            dropList = dropList + "<option value='" + i + "'>" + i + "</option>";
        }
        yearEl.html(dropList);//生成年份下拉菜单
        var monthly;
        for (month = 1; month < 13; month++) {
            monthly = monthly + "<option value='" + month + "'>" + month + "</option>";
        }
        monthEl.html(monthly);//生成月份下拉菜单
        var dayly;
        for (day = 1; day <= 31; day++) {
            dayly = dayly + "<option value='" + day + "'>" + day + "</option>";
        }
        dayEl.html(dayly);//生成天数下拉菜单
        yearEl.change(function () {
            monthEl.html(monthly);
            dayEl.html(dayly);
        });
        monthEl.change(function () {
            var currentDay;
            var Flag = yearEl.val();
            var currentMonth = monthEl.val();
            switch (currentMonth) {
                case "1" :
                case "3" :
                case "5" :
                case "7" :
                case "8" :
                case "10" :
                case "12" :
                    total = 31;
                    break;
                case "4" :
                case "6" :
                case "9" :
                case "11" :
                    total = 30;
                    break;
                case "2" :
                    if ((Flag % 4 == 0 && Flag % 100 != 0) || Flag % 400 == 0) {
                        total = 29;
                    } else {
                        total = 28;
                    }
                default:
                    break;
            }
            for (day = 1; day <= total; day++) {
                currentDay = currentDay + "<option value='" + day + "'>" + day + "</option>";
            }
            dayEl.html(currentDay);//生成日期下拉菜单
        })
    }

    //省市县三级联动
    areaChange();
    function areaChange() {
        var provinceEl = $("select[name=province]");
        var cityEl = $("select[name=city]");
        $.each(provinceJson, function (index, item) {
            var option = "<option value=" + item.id + ">" + item.province + "</option>";
            provinceEl.append(option);
        });
        provinceEl.change(function () {
            var selValue = $(this).val();
            $("input[name=dlprovince1]").val($("select[name=province]").find("option:selected").text());
            $("select[name=city] option:gt(0)").remove();
            $("input[name='dlcity1']").val('');
            $.each(cityJson, function (index, item) {
                if (item.parent == selValue || item.id == selValue) {
                    var option = "<option value=" + item.id + ">" + item.city + "</option>";
                    cityEl.append(option);
                }
            });
        });
        cityEl.change(function () {
            var selValue = $(this).val();
            $("input[name=dlcity1]").val('');
            if ($("select[name=city]").find("option:selected").val() != '0') {
                $("input[name=dlcity1]").val($("select[name=city]").find("option:selected").text());
            }
        });
    }


    function drawCircleQuery() {
        typhoonMap.drawCircle();
        typhoonMap.drawMarker();
        $.ajax({
            url: '/tf/main.json',
            //data: {latlngType:'1',lon:119.73485,lat:25.627117,llWidth:500},
            //data: {latlngType:'1',lon:119.775,lat:25.69583,llWidth:500}, //大练岛
            data: {latlngType: '1', lon: 119.48611, lat: 25.39722, llWidth: 500}, //兴化湾
            type: 'post',
            dataType: 'json',
            success: function (data) {

                $.ajax({
                    url: '/tf/main.json',
                    data: {latlngType: '1', lon: 119.775, lat: 25.69583, llWidth: 500}, //大练岛
                    // data: {latlngType: '1', lon: 119.48611, lat: 25.39722, llWidth: 500}, //兴化湾
                    type: 'post',
                    dataType: 'json',
                    success: function (data2) {
                        var datas = unionData(data.data, data2.data);
                        $("#data_list_ic_real").empty();//先清空数据
                        $("#data_label_ic_real").html("搜索到" + datas.length + "条相似路径台风");
                        if (datas.length > 0) {
                            $.each(datas, function (key, value) {
                                if (value.chnname == '' || value.chnname == 'null' || value.chnname == null) {
                                    value.chnname = '';
                                }
                                var html = '<li>' +
                                    '<div class="typhoon_no" bh="' + value.tfbh + '" ty="' + value.ty + '">' + value.tfbh + '</div>' +
                                    '<div class="typhoon_name">' + value.chnname + '&nbsp' + value.name + '</div>' +
                                    '</li>';
                                $("#data_list_ic_real").append(html);
                            });
                        }
                    }

                });

            }
        });
    }

    function unionData(dataArr1, dataArr2) {
        var dataMap = {};
        var resultArr = [];
        $.each(dataArr1, function (key, value) {
            var data = value;
            dataMap[value.tfbh] = data;
        });
        $.each(dataArr2, function (key, value) {
            var data = value;
            if (dataMap[value.tfbh] != null) {
                resultArr.push(data);
            }
        });
        return resultArr;
    }

});
